﻿// 打开终端查看输出信息，双击路径进行路径选择，上方为阿里云oss，下方为本地文件夹，选择本地文件夹显示后显示文件路径


using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SafeSyncPro
{
    public partial class Form1 : Form
    {
        private string selectedSourcePath; // 记录阿里云 OSS 选择的路径
        private string selectedTargetPath; // 记录本地文件夹选择的路径

        public Form1()
        {
            InitializeComponent();
            InitializeTreeView();
        }


        // 初始化 TreeView（异步加载阿里云 OSS 节点）
        private async void InitializeTreeView()
        {
            await LoadTreeViewAsync(treeViewOSS.Nodes, ""); // 加载阿里云 OSS 根节点
        }

        private async Task LoadTreeViewAsync(TreeNodeCollection nodes, string prefix)
        {
            try
            {
                var (folders, files) = await Task.Run(() => AliyunOSSUploader.ListObjects(prefix));

                // 添加文件夹节点
                foreach (var folder in folders)
                {
                    var folderNode = new TreeNode(Path.GetFileName(folder.TrimEnd('/')))
                    {
                        Tag = folder // 设置节点的路径
                    };

                    // 递归加载子文件夹内容
                    await LoadTreeViewAsync(folderNode.Nodes, folder);

                    nodes.Add(folderNode);
                }

                // 添加文件节点
                foreach (var file in files)
                {
                    var fileNode = new TreeNode(Path.GetFileName(file))
                    {
                        Tag = file // 设置节点的路径
                    };

                    nodes.Add(fileNode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载阿里云 OSS 节点失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 加载本地文件夹
        private void LoadLocalDirectory(TreeNode rootNode, string folderPath)
        {
            try
            {
                // 设置根节点的信息
                rootNode.Text = Path.GetFileName(folderPath); // 显示目录名称
                rootNode.Tag = folderPath;                    // 存储完整路径

                // 获取目录信息
                DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);

                // 添加子目录节点，并递归加载它们的内容
                foreach (var dir in directoryInfo.GetDirectories())
                {
                    var dirNode = new TreeNode(dir.Name)
                    {
                        Tag = dir.FullName // 设置节点的完整路径
                    };
                    rootNode.Nodes.Add(dirNode);

                    // 递归加载子目录内容
                    LoadLocalDirectory(dirNode, dir.FullName); // 递归
                }

                // 添加文件节点
                foreach (var file in directoryInfo.GetFiles())
                {
                    var fileNode = new TreeNode(file.Name)
                    {
                        Tag = file.FullName // 设置节点的完整路径
                    };
                    rootNode.Nodes.Add(fileNode);
                }

                // 让根节点展开以显示子目录
                rootNode.Expand();
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("访问被拒绝，无法加载部分文件或文件夹。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载本地文件夹失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        // TreeView 节点点击事件
        private void TreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode clickedNode = e.Node;

            if (sender == treeViewOSS)
            {
                selectedSourcePath = clickedNode.Tag?.ToString(); // 获取阿里云路径
                Console.WriteLine($"选中阿里云路径：{selectedSourcePath}");
            }
            else if (sender == treeViewLocal)
            {
                selectedTargetPath = clickedNode.Tag?.ToString(); // 获取本地路径
                Console.WriteLine($"选中本地路径：{selectedTargetPath}");
            }
        }

        // 选择本地文件夹并加载
        private void btnSelectLocalFolder_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string folderPath = folderBrowserDialog.SelectedPath;

                    // 清空 TreeView 并设置根节点为选中路径
                    treeViewLocal.Nodes.Clear();
                    TreeNode rootNode = new TreeNode();
                    treeViewLocal.Nodes.Add(rootNode);

                    // 加载选中目录
                    LoadLocalDirectory(rootNode, folderPath);

                    // 展开根节点
                    rootNode.Expand();
                }
            }
        }

        // 上传单个文件
        private void btnUploadFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "所有文件|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName;
                    string objectName = Path.GetFileName(filePath);
                    AliyunOSSUploader.UploadFile(filePath, objectName);
                    RefreshTreeView();
                }
            }
        }

        // 上传文件夹
        private void btnUploadFolder_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string folderPath = folderBrowserDialog.SelectedPath;
                    AliyunOSSUploader.UploadDirectory(folderPath);
                    RefreshTreeView();
                }
            }
        }

        // 刷新阿里云 TreeView
        private async void RefreshTreeView()
        {
            treeViewOSS.Nodes.Clear();
            await LoadTreeViewAsync(treeViewOSS.Nodes, "");
        }

        // 同步文件夹
        private void btnSync_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(selectedSourcePath) || string.IsNullOrEmpty(selectedTargetPath))
            {
                MessageBox.Show("请先选择源路径和目标路径！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 调用同步功能
            AliyunOSSUploader.SyncFolders(selectedTargetPath, selectedSourcePath);
            RefreshTreeView();
        }


    }
}